import { Axios, AxiosRequestConfig, AxiosResponse } from 'axios';
import httpFetch from './connections/httpFetch';
import mockFetch from './connections/mockFetch';

enum HttpSource { Java, Mock }

const connectMap = new Map<HttpSource, Axios>();
connectMap.set(HttpSource.Java, httpFetch);
connectMap.set(HttpSource.Mock, mockFetch as Axios);

interface Response<T> {
    errorCode: number
    errorInfo: string
    errorPath: string
    result: T
}

class Http {
    static other = {
        headers: {
            'Content-Type': 'application/json',
            reqFieldKeyType: 'underscore',
        }
    }

    static async get<T = any, D = any>(
        source: HttpSource, url: string, config?: AxiosRequestConfig<D>
    ) {
        const fetch = connectMap.get(source);
        const res = await fetch?.get<T, Response<T>, D>(url, { ...this.other, ...config });
        return res
    }

    // post默认'Content-Type': 'application/x-www-form-urlencoded'，可修改headers为'application/json'
    // 如果是文件上传，可以修改headers为 headers: { 'Content-Type': 'multipart/form-data' }
    static async post<T = any, D = any>(
        source: HttpSource, url: string, data?: D, config?: AxiosRequestConfig<D>
    ) {
        const fetch = connectMap.get(source);
        const res = await fetch?.post<T, Response<T>, D>(url, data, { ...this.other, ...config });
        return res
    }
}

export default {
    Http,
    HttpSource
};

export {
    Http,
    HttpSource
}